<?php

namespace App\Jobs;

use Illuminate\Bus\Queueable;
use Illuminate\Queue\SerializesModels;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;

class AddOrderJob implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;

    protected $user;
    protected $id;
    protected $address;
    public function __construct($address,$id,$user)
    {
        $this->user=$user;
        $this->address=$address;
        $this->id=$id;
    }
    public function handle()
    {
        $ids = explode(',', $this->id);
        $carts = Cart::whereIn('id', $ids)->with('getGoods', 'getProducts')->get()->toArray();
        $totals = 0;
        foreach ($carts as $cart) {
            $totals = $totals + $cart['number'] * $cart['get_goods']['price'];
        }
        $order = Order::create([
            'orderNumber' => md5(time()),
            'total' => $totals,
            'address' => $this->address,
            'status' => 0,
            'user_id' =>$this->user,
        ]);
        //再添加到订单列表里
        foreach ($carts as $cart) {
            $orderList = OrderList::create([
                'order_id' => $order->id,
                'goods_id' => $cart['goods_id'],
                'product_id' => $cart['product_id'],
                'number' => $cart['number'],
                'user_id' => $this->user,
            ]);
        }
        foreach ($carts as $cart) {
            $product = Product::find($cart['product_id']);
            $product->update(['inventory' => $product['inventory'] - $cart['number']]);
            $cart->destroy();
        }
    }
}
